import React, { useState, useMemo, useRef } from 'react';
import { connect } from 'umi';
import { MaterialManageAPI } from '../common/type';
import { MaterialManageServices } from '../services';
import { SchemaManage } from '@/components/SchemaComponent';
import { MaterialManageTabSwitch, getTableColumns } from '../mconfig';
import { PlusOutlined, UploadOutlined, FileProtectOutlined } from '@ant-design/icons';
import DetailsDrawer from './DetailsDrawer';
import UpdataMaterialModal from './UpdataModal';
import ApplySignModal from './SignModal';
import { UploadFileModal } from './UploadFileModal';
import { ILoadMapTypeAll } from '@/common';
import { CancelModal } from '@/components/CancelTextModal';
import { UploadModal } from './UploadModal';
import { BatchImportModal } from '@/components/BatchImportModal';
import { MaterialCheckModal } from './MaterialCheckModal';
import { message } from 'antd';

const MaterialManageView: React.FC<MaterialManageAPI.IMaterialManageView> = ({ curRes }) => {
  /**管理页services*/
  const { data, loading, searchList, pagination, reloadRequest, manageTableParams } = MaterialManageServices(curRes);

  /**管理页的ref*/
  const MaterialManageViewRef: any = useRef();

  /**新增弹窗的显示*/
  const [isShowAddModal, setIsShowAddModal] = useState({
    isShow: false,
    recordObj: {},
    clickType: '',
  });

  /**是否显示详情抽屉*/
  const [isShowDetail, setIsShowDetail] = useState<Record<string, any>>({
    isShow: false,
    recordObj: {},
  });

  /**是否显示作废弹窗*/
  const [isShowCancelModal, setIsShowCancelModal] = useState<Record<string, any>>({
    isShow: false,
    recordObj: {},
  });

  /**发布，申请弹窗*/
  const [isShowApplyModal, setIsShowApplyModal] = useState<Record<string, any>>({
    isShow: false,
    recordObj: {},
    type: null,
    select: null,
  });

  /**是否显示 - 批量审核弹窗*/
  const [isShowCheckModal, setIsShowCheckModal] = useState<Record<string, any>>({
    isShow: false,
    resObj: null,
  });

  /**批量上传弹窗*/
  const [isShowBatch, setIsShowBatch] = useState<boolean>(false);

  /** 表格选中内容 */
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);

  /** 表格选中record */
  const [selectRows, setSelectRows] = useState<Record<string, any>[]>([]);

  /**头部权限切换*/
  const switchList: MaterialManageAPI.IManageTabsSwitchType = useMemo(() => {
    return MaterialManageTabSwitch(curRes);
  }, [curRes]);

  /**切换头部方法*/
  const onSwitch = (key: string | undefined | number, searchValues: any, params: any) => {
    reloadRequest({ ...params, ...searchValues });
  };

  /**重置方法*/
  const onReset = (reqParams: MaterialManageAPI.IAssetTableRequestType) => {
    reloadRequest({ ...reqParams });
  };

  /**搜索方法*/
  const onSearch = (reqParams: MaterialManageAPI.IAssetTableRequestType) => {
    reloadRequest({ ...reqParams });
  };

  /**刷新管理页面的办法*/
  const reloadManage = () => {
    reloadRequest({ ...manageTableParams });
  };

  /**分页方法*/
  const onPageChange = (current: any, pageSize: any, params: any) => {
    reloadRequest({ pageSize, current, ...params });
  };

  /**Table操作列的事件池*/
  const getTableOperateFuncs: MaterialManageAPI.IMaterialTableActionType = {
    /**详情按钮*/
    onView(record) {
      setIsShowDetail({
        isShow: true,
        recordObj: record,
      });
    },
    /**编辑按钮*/
    onEdit(record) {
      setIsShowAddModal({
        isShow: true,
        recordObj: record,
        clickType: 'edit',
      });
    },
    /**作废按钮*/
    onCancel(record) {
      setIsShowCancelModal({
        isShow: true,
        recordObj: record,
      });
    },
    /**发布*/
    onPublish(record) {
      setIsShowApplyModal({
        isShow: true,
        recordObj: record,
        type: 'publish',
      });
    },
    /**申请*/
    onApply(record) {
      setIsShowApplyModal({
        isShow: true,
        recordObj: record,
        type: 'apply',
        select: 'id',
      });
    },
  };

  /**Table的columns集合*/
  const getTableColumn: Record<string, any>[] = useMemo(() => {
    return getTableColumns(curRes, getTableOperateFuncs);
  }, [curRes]);

  /**新增操作按钮*/
  const actionList: MaterialManageAPI.IActionList = useMemo(() => {
    return [
      {
        title: '添加',
        visible: curRes?.['/materialController/add'] || false,
        type: 'primary',
        icon: <PlusOutlined />,
        onClick: () => {
          setIsShowAddModal({
            isShow: true,
            recordObj: {},
            clickType: 'add',
          });
        },
      },
      {
        title: '导入',
        visible: curRes?.['/materialController/directImport'] && curRes?.['/materialController/batchImportMaterial'] ? true : false,
        type: 'primary',
        icon: <UploadOutlined />,
        onClick: () => {
          setIsShowBatch(true);
        },
      },
      {
        title: '审核',
        visible: curRes?.['/materialController/audit'] || false,
        type: 'primary',
        icon: <FileProtectOutlined />,
        onClick: () => {
          if (selectedRowKeys?.length) {
            setIsShowCheckModal({
              isShow: true,
              resObj: selectRows,
            });
          } else {
            message?.error('请选择物料进行审核！');
          }
        },
      },
    ];
  }, [curRes, selectedRowKeys]);

  /**
   * 物料导入-校验接口需要当前上传人是否有发布的权限
   * */
  const materialState = useMemo(() => {
    if (!curRes) return {};
    if (curRes?.['/materialController/publish']) return { materialState: 2 };
    if (curRes?.['/materialController/applyMaterial']) return { materialState: 1 };
    return { materialState: 0 };
  }, [curRes]);

  return (
    <div
      id={'custom-preview-container'}
      style={{
        position: 'relative',
        overflow: 'hidden',
        height: '100%',
        width: '100%',
      }}
    >
      <SchemaManage
        ref={MaterialManageViewRef}
        searchProps={{
          switchList,
          searchList,
          onSwitch,
          onReset,
          onSearch,
        }}
        actionList={actionList}
        tableProps={{
          columns: getTableColumn,
          dataSource: data?.rows, //mockData
          rowKey: 'id',
          loading: loading,
          pagination: pagination as any,
          onPageChange: onPageChange,
          rowSelection: curRes?.['/materialController/audit']
            ? {
                type: 'checkBox',
                selectedRowKeys,
                onSelect: (record: any, selected: any) => {
                  if (selected) {
                    /** 添加 */
                    setSelectedRowKeys([...selectedRowKeys, record?.id]); // 保存key
                    setSelectRows([...selectRows, record]); // 保存record
                  } else {
                    /** 去除 */
                    const rowsList = selectRows?.filter((item) => record?.id != item?.id);
                    setSelectedRowKeys(rowsList?.map((i: Record<string, any>) => i?.id));
                    setSelectRows(rowsList);
                  }
                },
                onSelectAll: (selected: any, selectedRows: any, changeRows: any) => {
                  let dataKeys: any[] = []; // 当前table渲染的数据key集合
                  data?.rows?.forEach((item: Record<string, any>) => {
                    dataKeys?.push(item?.id);
                  });
                  if (selected) {
                    //全选
                    // 两个key合并去重
                    let keylist = Array.from(new Set([...dataKeys, ...selectedRowKeys]));
                    setSelectedRowKeys(keylist);
                    // 处理record
                    setSelectRows([...selectRows, ...changeRows]);
                  } else {
                    //全不选
                    // 处理key
                    let newarr: any[] = selectedRowKeys?.filter((item) => {
                      return !dataKeys?.includes(item);
                    });
                    setSelectedRowKeys(newarr);
                    /**
                     * 处理row 这里的changeRows代表被取消的rows集合
                     * {keys} 拿的是被取消的rows集合的id集合
                     * 再已经选择的数据中进行过滤
                     * */
                    let keys: any[] = [];
                    changeRows?.forEach((item: any) => {
                      keys?.push(item?.id);
                    });
                    const newRows = selectRows?.filter((item) => {
                      return keys?.indexOf(item?.id) == -1;
                    });
                    setSelectRows(newRows);
                  }
                },
                getCheckboxProps: (record) => {
                  return {
                    disabled: record?.state != 1,
                  };
                },
              }
            : undefined,
        }}
      />

      {/* 批量上传（old）isShowBatch */}
      {false && (
        <UploadModal
          curRes={curRes}
          reloadManage={reloadManage}
          onClose={() => {
            setIsShowBatch(false);
          }}
        />
      )}

      {/* 批量上传（new）*/}
      {isShowBatch && (
        <BatchImportModal
          curRes={curRes}
          modalTitle={'批量导入物料'}
          onClose={() => setIsShowBatch(false)}
          templateUrl={'/materialController/downloadFile'}
          parserImportUrl={'/materialController/directImport'}
          batchImportUrl={'/materialController/batchImportMaterial'}
          refreshCallback={() => reloadManage()}
          filePath={'/minfile/purchase/template/物料信息导入模板.xlsx'}
          batchReqHeader={materialState}
        />
      )}

      {/* 查看详情抽屉 */}
      <DetailsDrawer
        curRes={curRes}
        onClose={() => {
          setIsShowDetail({
            isShow: false,
            recordObj: {},
          });
        }}
        isShowDetail={isShowDetail?.isShow}
        recordObj={isShowDetail?.recordObj}
        reloadManage={reloadManage}
      />

      {/* 新增编辑弹窗 */}
      {isShowAddModal?.isShow && (
        <UpdataMaterialModal
          curRes={curRes}
          onClose={() => {
            setIsShowAddModal({
              isShow: false,
              recordObj: {},
              clickType: '',
            });
          }}
          checkRows={isShowAddModal?.recordObj}
          isShowModal={isShowAddModal?.isShow}
          reloadManage={reloadManage}
        />
      )}

      {/* 作废弹窗 */}
      {isShowCancelModal?.isShow && (
        <CancelModal
          checkRows={isShowCancelModal?.recordObj}
          cancelTypeDic={ILoadMapTypeAll.MATERIAL_CANCEL}
          cancelFormTypeRequired={true}
          cancelFormReasonRequired={true}
          modalTitle={'作废物料'}
          cancelText={isShowCancelModal?.recordObj?.fullName || null}
          cancelRequestUrl={'/materialController/cancel'}
          reloadManage={reloadManage}
          cancelRequestType="PUT"
          onClose={() => {
            setIsShowCancelModal({
              isShow: false,
              signTitle: '',
            });
          }}
        />
      )}

      {/* 发布申请弹窗 */}
      {isShowApplyModal?.isShow && (
        <ApplySignModal
          curRes={curRes}
          onClose={() => {
            setIsShowApplyModal({
              isShow: false,
              recordObj: {},
              type: null,
            });
          }}
          checkRows={isShowApplyModal?.recordObj}
          isShowModal={isShowApplyModal?.isShow}
          reloadManage={reloadManage}
          modalType={isShowApplyModal?.type}
          isShowIdName={isShowApplyModal?.select}
          onCloseModalParent={() => {}}
        />
      )}

      {/* 批量审核弹窗 */}
      {isShowCheckModal?.isShow && (
        <MaterialCheckModal
          onClose={(flag) => {
            if (flag) {
              setSelectedRowKeys([]);
              setSelectRows([]);
              reloadManage();
              return;
            }
            setIsShowCheckModal({});
          }}
          selectKeys={isShowCheckModal?.resObj}
        />
      )}
    </div>
  );
};

export default connect(({ baseLogin, navTab }: Record<string, any>) => ({
  curRes: baseLogin?.permissions,
  navTab,
}))(MaterialManageView);
